// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  // 1. 根据 openid 获取对应的用户
  const usersDb = cloud.database().collection('users')
  const userData = await usersDb.where({
    openid
  }).get()
  const user = userData.data[0]
  // 2. 根据 用户的 comments 获取对应的 comments
  const commentsDb = cloud.database().collection('comments')
  const booksDb = cloud.database().collection('books')
  const comments = []
  for (let i = 0; i < user.comments.length; i++) {
    const commentData = await commentsDb.where({
      commentId: user.comments[i].commentId
    }).get()
    const comment = commentData.data[0]
    // 3. 根据 comments 的书本的 id 获得书本封面
    const coverData = await booksDb.where({
      bookId: comment.bookId
    }).field({
      coverUrl: true
    }).get()
    // 4. 修饰内容并返回
    comment.coverUrl = coverData.data[0].coverUrl
    comments.push(comment)
  }


  return comments
}